package com.tuanquan.flutter_plugin_tengxunvideo.pusher;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tuanquan.flutter_plugin_tengxunvideo.pusher.model.CameraPush;
import com.tuanquan.flutter_plugin_tengxunvideo.pusher.model.CameraPushImpl;

import java.io.File;
import java.util.Map;

import io.flutter.Log;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 * 获取临时的推拉流地址     这个只能用一次，用过立马换
 * GET
 * Header    Content-Type： application/json; charset=utf-8
 * https://lvb.qcloud.com/weapp/utils/get_test_pushurl
 *
 */
public class FlutterTXCloudVideoView implements PlatformView, MethodChannel.MethodCallHandler, CameraPush.OnLivePusherCallback {


    //推流的View
    private final TXCloudVideoView pusherView;
    //控制推流
    private final CameraPushImpl mLivePusher;
    //
    private static final String BIND_ID_TO_NAME = "plugins.player/FlutterTXCloudVideoView";

    // 对应 SDK 的画质列表（TXLiveConstants中定义）
    private static final int[] VIDEO_QUALITY_TYPE_ARR = new int[]{
            TXLiveConstants.VIDEO_QUALITY_ULTRA_DEFINITION,
            TXLiveConstants.VIDEO_QUALITY_SUPER_DEFINITION,
            TXLiveConstants.VIDEO_QUALITY_HIGH_DEFINITION,
            TXLiveConstants.VIDEO_QUALITY_STANDARD_DEFINITION,
            TXLiveConstants.VIDEO_QUALITY_LINKMIC_MAIN_PUBLISHER,
            TXLiveConstants.VIDEO_QUALITY_LINKMIC_SUB_PUBLISHER,
            TXLiveConstants.VIDEO_QUALITY_REALTIEM_VIDEOCHAT};
    //回调给你的控制器
    private final MethodChannel methodChannel;


    public FlutterTXCloudVideoView(Context context, BinaryMessenger messenger, int id, Map<String, Object> params, Activity activity) {
        pusherView = new TXCloudVideoView(activity);
        mLivePusher = new CameraPushImpl(activity, pusherView);

        methodChannel = new MethodChannel(messenger, BIND_ID_TO_NAME + id);

        //初始化推流设置
        initPusher(params);

        /**
         *  初始化的时候自动播放,如果不需要可以注释掉
         */
        mLivePusher.startPush();
    }

    private void initPusher(Map<String, Object> params) {
        //设置是否开启静音推流
        Boolean mute = (Boolean) params.get("mute");
        if (mute == null) {
            mute = false;
        }
        mLivePusher.setMute(mute);
        //设置开启或关闭观众端镜像
        Boolean mirror = (Boolean) params.get("mirror");
        if (mirror != null) {
            mLivePusher.setMirror(mirror);
        }
        //水印
        Boolean watermark = (Boolean) params.get("watermark");
        if (watermark == null) {
            watermark = false;
        }
        mLivePusher.setWatermark(watermark);
        //设置开启或关闭手动对焦
        Boolean touchFocus = (Boolean) params.get("touchFocus");
        if (touchFocus == null) {
            touchFocus = true;
        }
        mLivePusher.setTouchFocus(touchFocus);
        //设置开启或关闭双手缩放
        Boolean enableZoom = (Boolean) params.get("enableZoom");
        if (enableZoom == null) {
            enableZoom = false;
        }
        mLivePusher.setEnableZoom(enableZoom);
        //启用纯音频推送
        Boolean enablePureAudioPush = (Boolean) params.get("enablePureAudioPush");
        if (enablePureAudioPush == null) {
            enablePureAudioPush = false;
        }
        mLivePusher.enablePureAudioPush(enablePureAudioPush);
        //设置耳返开关
        Boolean enableAudioEarMonitoring = (Boolean) params.get("enableAudioEarMonitoring");
        if (enableAudioEarMonitoring == null) {
            enableAudioEarMonitoring = false;
        }
        mLivePusher.enableAudioEarMonitoring(enableAudioEarMonitoring);
        //设置视频编码质量
        Boolean adjustBitrate = (Boolean) params.get("adjustBitrate");
        if (adjustBitrate == null) {
            adjustBitrate = true;
        }
        Integer type = (Integer) params.get("type");
        if (type == null) {
            type = 1;
        }
        mLivePusher.setQuality(adjustBitrate, VIDEO_QUALITY_TYPE_ARR[type]);
        /**
         * 设置音质选择（声道设置）
         * 语音(speech)：16000，单声道
         * 标准(default)：48000，单声道
         * 音乐(music)：48000，双声道
         *
         * @param channel    单声道  1                              双声道 2
         * @param sampleRate 音频采样率  16000  48000                48000
         */
        Integer audioChannels = (Integer) params.get("audioChannels");
        Integer sampleRate = (Integer) params.get("sampleRate");
        if (audioChannels == null) {
            //默认单声道
            audioChannels = 2;
        }
        if (sampleRate == null) {
            sampleRate = 48000;
        }
        mLivePusher.setAudioQuality(audioChannels, sampleRate);

        Boolean homeOrientation = (Boolean) params.get("homeOrientation");
        if (homeOrientation != null) {
            mLivePusher.setHomeOrientation(homeOrientation);
        }
        //打开闪光灯  默认不打开
        Boolean isFlashEnable = (Boolean) params.get("isFlashEnable");
        if (isFlashEnable != null) {
            mLivePusher.turnOnFlashLight(isFlashEnable);
        }
        //是否开启硬件加速
        Boolean hardwareAcceleration = (Boolean) params.get("hardwareAcceleration");
        if (hardwareAcceleration != null) {
            mLivePusher.setHardwareAcceleration(hardwareAcceleration);
        }
        mLivePusher.setOnLivePusherCallback(this);
        //推流地址
        String mPusherURL = (String) params.get("pusherURL");
        if (TextUtils.isEmpty(mPusherURL)) {
            throw new NullPointerException("pusherURL 不能为null");
        }
        mLivePusher.setURL(mPusherURL);

    }

    //你调我的方法
    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        switch (call.method) {
            case "startPush":
                //无返回值
                mLivePusher.startPush();
                result.success(null);
                break;
            case "isPushing":
                //有返回值
                boolean pushing = mLivePusher.isPushing();
                result.success(pushing);
                break;

            default:
                result.notImplemented();
        }

    }

    @Override
    public View getView() {
        return pusherView;
    }

    @Override
    public void dispose() {
        if (mLivePusher != null) {
            mLivePusher.destroy();
        }
    }

    @Override
    public void onPushStart(int code) {
        methodChannel.invokeMethod("onPushStart", code);
    }

    @Override
    public void onPushResume() {
        methodChannel.invokeMethod("onPushResume", null);
    }

    @Override
    public void onPushPause() {
        methodChannel.invokeMethod("onPushPause", null);
    }

    @Override
    public void onPushStop() {
        methodChannel.invokeMethod("onPushStop", null);
    }

    @Override
    public void onSnapshot(File file) {
        //截图  传回去的是一个String的文件绝对路径  （不知道能不能直接传file）
        methodChannel.invokeMethod("onSnapshot", file.getAbsolutePath());
    }

    @Override
    public void onPushEvent(int event, Bundle param) {
        methodChannel.invokeMethod("onPushEvent", event);
    }

    @Override
    public void onNetStatus(Bundle status) {
        methodChannel.invokeMethod("onNetStatus", null);
    }

    @Override
    public void onActivityRotationObserverChange(boolean selfChange) {
        methodChannel.invokeMethod("onActivityRotationObserverChange", selfChange);
    }
}
